import logging
import re
import sys

from PyQt5.QtCore import Qt, pyqtSignal, QDir
from PyQt5.QtWidgets import QApplication, QFileDialog, QFileIconProvider, QVBoxLayout, QPushButton, QLabel, QListView, \
    QFrame, QWidget, QFileSystemModel


class PyAndTxtFileFilterModel(QFileSystemModel):
    def __init__(self, parent=None, type_list=None):
        super(PyAndTxtFileFilterModel, self).__init__(parent)
        self.setRootPath("./resources")
        self.setFilter(QDir.Files | QDir.Dirs | QDir.NoDotAndDotDot | QDir.NoSymLinks)
        self.setNameFilters(type_list)


class FileBrowser(QWidget):
    """
    type_list；过滤列表
    file_path；本地文件打开的默认目录
    WorkerName；模块调用标签
    """
    filepath_Signal = pyqtSignal(str)

    def __init__(self, parent=None, type_list=None, file_path="../resources/videos", WorkerName='video'):
        super(FileBrowser, self).__init__(parent)
        self.file_path = None
        self.new_path = None
        self.Worker_image = None
        self.Worker_video = None
        self.index = None
        self.WorkerName = WorkerName
        self.fileModel = None  # 初始化本地文件模型

        # 创建组件
        self.listview1 = QListView()
        self.openFolderButton = QPushButton("切换目录", self)  # 创建打开文件夹按钮
        self.vertical_separator = QFrame()  # 水平分割
        self.label1 = QLabel('本地文件')

        # 创建文件浏览器
        self.local_file_model(type_list, file_path=file_path)

        # 创建 QVBoxLayout 并将 QListView1->2 和按钮添加到布局中
        layout = QVBoxLayout(self)
        layout.addWidget(self.label1)
        self.label1.setAlignment(Qt.AlignCenter)  # 设置标签文本居中
        layout.addWidget(self.listview1, 2)
        layout.addWidget(self.openFolderButton)
        layout.addWidget(self.vertical_separator)

        # 连接信号槽
        # self.listview1.doubleClicked.connect(self.openDirectory)
        # self.openFolderButton.clicked.connect(self.onOpenFolderButtonClicked)

    def local_file_model(self, type_list, file_path="/"):
        """
        创建本地文件模型
        :param file_path: 文件浏览器默认打开的地址
        :param type_list: 不过滤文件的后缀列表
        """
        self.fileModel = PyAndTxtFileFilterModel(type_list=type_list)
        self.fileModel.setRootPath("/")
        self.fileModel.setIconProvider(QFileIconProvider())
        self.listview1.setModel(self.fileModel)  # 创建本地文件浏览器
        self.listview1.setRootIndex(self.fileModel.index(file_path))

    def onOpenFolderButtonClicked(self):
        """
        使用 QFileDialog 获取用户选择的本地文件夹路径
        """
        directoryPath = QFileDialog.getExistingDirectory(self, "选择文件夹", None, QFileDialog.ShowDirsOnly)
        if directoryPath:  # 检查用户是否选择了目录
            print("选择的目录是:", directoryPath)
            # 可以在这里添加代码处理选择的目录
        else:
            print("用户取消了操作")
        if directoryPath:
            self.fileModel.setRootPath(directoryPath)  # 更新文件模型的根路径
            self.listview1.clearSelection()  # 清除 QListView 的选择
            self.listview1.setRootIndex(
                self.fileModel.index(directoryPath))  # 更新 QListView 的根索引
            self.fileModel.setRootPath(directoryPath)
            print(directoryPath)

    def openDirectory(self, index):
        """
        获取本地文件地址，并启动模型
        :param index:
        """
        try:
            self.file_path = self.fileModel.filePath(index)
            self.new_path = re.sub(r'[^\\/.]*$', '', self.file_path)
            # main.extract_audio(video_path=file_path, audio_path=new_path)
            # AudioFormatSelector().show()
            # self.hide()
        except Exception as e:
            logging.info(f'模块参数错误{e}')
            print("Selected:", self.new_path)
        print(self.file_path, self.new_path)


music_formats = ("mp3, wav, wma, aac, aiff, m4a, ogg, flac, alac, ape,amr, midi, mka, mp2, ofr, ra, rm, shn, tta, wv,"
                 " webm")
if __name__ == '__main__':
    app = QApplication(sys.argv)
    # main_window = QMainWindow()
    WorkerName = 'video'
    if WorkerName == 'video':
        type_list = ['*.mp4', '*.avi', '*.mkv', '*.mov', '*.wmv', '*.flv', '*.f4v', '*.webm', '*.m4v',
                     '*.ts', '*.mpeg', '*.mpe', '*.mpg', '*.rm', '*.rmvb', '*.vob', '*.m2ts', '*.dts']
        file_path = "./resources"
        main_window = FileBrowser(type_list=type_list, file_path=file_path, WorkerName=WorkerName)
        main_window.show()  # 显示主窗口
        sys.exit(app.exec_())